<?php  
class Poll_CommentController extends Core_Controller_Action_Standard
{
    public function init()
    {
        $viewer = Engine_Api::_()->user()->getViewer();
        $type = $this->_getParam('type');
        $identity = $this->_getParam('id');
        if( $type && $identity ) {
            $item = Engine_Api::_()->getItem($type, $identity);
            if( $item instanceof Core_Model_Item_Abstract && 
            (method_exists($item, 'comments') || method_exists($item, 'likes')) ) {
                if( !Engine_Api::_()->core()->hasSubject() ) {
                    Engine_Api::_()->core()->setSubject($item);
                }                                                                         
            }
        }
                                     
        $this->_helper->requireSubject();
    }

    public function listAction()
    {
        $viewer = Engine_Api::_()->user()->getViewer();
        $subject = Engine_Api::_()->core()->getSubject();

        // Perms
        $this->view->canComment = $canComment = $subject->authorization()->isAllowed($viewer, 'comment');
        $this->view->canDelete = $subject->authorization()->isAllowed($viewer, 'edit');

        // Likes
        $this->view->viewAllLikes = $this->_getParam('viewAllLikes', false);
        $this->view->likes = $likes = $subject->likes()->getLikePaginator();

        // Comments

        // If has a page, display oldest to newest
        if( null !== ( $page = $this->_getParam('page')) )
        {
            $commentSelect = $subject->comments()->getCommentSelect();
            $commentSelect->order('comment_id ASC');
            $comments = Zend_Paginator::factory($commentSelect);
            $comments->setCurrentPageNumber($page);
            $comments->setItemCountPerPage(10);
            $this->view->comments = $comments;
            $this->view->page = $page;
        }

        // If not has a page, show the
        else
        {
            $commentSelect = $subject->comments()->getCommentSelect();
            $commentSelect->order('comment_id DESC');
            $comments = Zend_Paginator::factory($commentSelect);
            $comments->setCurrentPageNumber(1);
            $comments->setItemCountPerPage(4);
            $this->view->comments = $comments;
            $this->view->page = $page;
        }

        if( $viewer->getIdentity() && $canComment ) {
            $this->view->form = $form = new Core_Form_Comment_Create();
            $form->populate(array(
            'identity' => $subject->getIdentity(),
            'type' => $subject->getType(),
            ));
        }
        
        if ($this->_getParam('method') == 'ajax') {
            $this->view->body = $this->view->render('comment/list.tpl');  
        } 
    }
}